from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime
from dev.solution_integrate import SolutionIntegrate,json_load
from dev.stock_visual.email_send import EmailSender
from dev.stock_visual.oss import OSS

from pathlib import Path
import sys
import os
curPath = os.path.abspath(os.path.dirname(__file__))
rootPath = os.path.split(curPath)[0]
sys.path.append(rootPath)

saveDir = os.path.join(curPath, "resources")

#自动生成分析股票分析报表
def generate_stock_report():
    print(datetime.now().strftime("%Y-%m-%d %H:%M:%S"))

    # saveDir = os.path.join(curPath, "resources")
    res_dict = json_load(os.path.join(saveDir, "stock_config.json"))  # 加载json配置文件

    codes = res_dict['codes']
    stocks_config = res_dict["stocks_config"]

    emailSender_config = res_dict['emailSender']
    emailSender = EmailSender(
        mail_host=emailSender_config["mail_host"],
        mail_user=emailSender_config["mail_user"],
        mail_pass=emailSender_config["mail_pass"],
        sender=emailSender_config["sender"])  # 初始化一个邮件发送对象
    # 初始化一封信
    emailSender.init_email(receivers=emailSender_config["receivers"], content=emailSender_config["content"],
                           subject=emailSender_config["subject"])

    # 阿里云OSS使用流程 参考 https://zhuanlan.zhihu.com/p/567771838
    aliyun_oss_config = res_dict['aliyun_oss']
    ACCESS_KEY_ID = aliyun_oss_config[
        "ACCESS_KEY_ID"]  # RAM账号access_key_id,如果没有用主账号登录工作台创建并授权，关于RAM角色参考 https://ram.console.aliyun.com/roles
    ACCESS_KEY_SECRET = aliyun_oss_config["ACCESS_KEY_SECRET"]  # RAM账号access_key_secret
    ENDPOINT = aliyun_oss_config["ENDPOINT"]  # 可以在bucket中获取地域节点endpoint 参考 https://zhuanlan.zhihu.com/p/567771838
    BUCKET_NAME = aliyun_oss_config["BUCKET_NAME"]
    oss_obj = OSS(access_key_id=ACCESS_KEY_ID, access_key_secret=ACCESS_KEY_SECRET, endpoint=ENDPOINT,
                  bucket_name=BUCKET_NAME)

    integrate = SolutionIntegrate(codes=codes, saveDir=saveDir, stocks_config=stocks_config, emailSender=emailSender,
                                  oss_obj=oss_obj)  # 初始化方案集成对象
    # 发送一封股票分析报告
    integrate.integrate()

if __name__ == '__main__':
    # 定时运行job方法，实现周一~周五下午6点自动生成分析股票分析报表
    # BlockingScheduler
    sched_json = json_load(os.path.join(saveDir,"scheduler_config.json"))
    scheduler = BlockingScheduler()
    print("starting....")
    # cron: 在特定时间周期性地触发 参考https://blog.csdn.net/m0_56312629/article/details/124737291
    day_of_week = sched_json["day_of_week"]   #"0-5"表示从星期一(0)到星期五(4)
    hour = sched_json["hour"]
    minute = sched_json["minute"]
    scheduler.add_job(generate_stock_report, 'cron', day_of_week=day_of_week, hour=hour, minute=minute)
    scheduler.start()
    # generate_stock_report()